<?php

namespace app\store\controller;

use app\store\model\Goods as GoodsModel;
use app\store\model\Category as CategoryModel;
use app\store\service\Goods as GoodsService;

/**
 * 商品管理控制器
 * Class Goods
 * @package app\store\controller
 */
class Goods extends Controller
{
    /**
     * 商品列表(出售中)
     * @return mixed
     * @throws \think\exception\DbException
     */
    public function index()
    {
        // 获取全部商品列表
        $model = new GoodsModel;
        $list = $model->getList(array_merge(['status' => -1], $this->request->param()));
        // 商品分类
        $catgory = CategoryModel::getCacheTree();
        return $this->fetch('index', compact('list', 'catgory'));
    }

    /**
     * 添加商品
     * @return array|mixed
     * @throws \think\exception\PDOException
     */
    public function add()
    {
        if (!$this->request->isAjax()) {
            return $this->fetch(
                'add',
                array_merge(GoodsService::getEditData(null, 'add'), [])
            );
        }
        $model = new GoodsModel;
        if ($model->add($this->postData('goods'))) {
            session('detailed', null);
            return $this->renderSuccess('添加成功', url('goods/index'));
        }
        return $this->renderError($model->getError() ?: '添加失败');
    }

    /**
     * 一键复制
     * @param $goods_id
     * @return array|mixed
     * @throws \think\exception\PDOException
     */
    public function copy($goods_id)
    {
        // 商品详情
        $model = GoodsModel::detail($goods_id);
        if (!$this->request->isAjax()) {
            return $this->fetch(
                'edit',
                array_merge(GoodsService::getEditData($model, 'copy'), compact('model'))
            );
        }
        $model = new GoodsModel;
        if ($model->add($this->postData('goods'))) {
            return $this->renderSuccess('添加成功', url('goods/index'));
        }
        return $this->renderError($model->getError() ?: '添加失败');
    }

    /**
     * 商品编辑
     * @param $goods_id
     * @return array|bool|mixed
     */
    public function edit($goods_id)
    {
        // 商品详情
        $model = GoodsModel::detail($goods_id);
        if (!$this->request->isAjax()) {
            return $this->fetch(
                'edit',
                array_merge(GoodsService::getEditData($model), compact('model'))
            );
        }
        // 更新记录
        if ($model->edit($this->postData('goods'))) {
            return $this->renderSuccess('更新成功', url('goods/index'));
        }
        return $this->renderError($model->getError() ?: '更新失败');
    }

    /**
     * 修改商品状态
     * @param $goods_id
     * @param boolean $state
     * @return array
     */
    public function state($goods_id, $state)
    {
        // 商品详情
        $model = GoodsModel::detail($goods_id);
        if (!$model->setStatus($state)) {
            return $this->renderError('操作失败');
        }
        return $this->renderSuccess('操作成功');
    }

    /**
     * 删除商品
     * @param $goods_id
     * @return array
     */
    public function delete($goods_id)
    {
        // 商品详情
        $model = GoodsModel::detail($goods_id);
        if (!$model->setDelete()) {
            return $this->renderError($model->getError() ?: '删除失败');
        }
        return $this->renderSuccess('删除成功');
    }


    /**
     * 添加淘宝商品详细
     * @return array|mixed
     * @throws \think\exception\PDOException
     */
    public function taobaoadd()
    {
        ignore_user_abort();
        set_time_limit(0);
        $id = trim(input('url'));
        $url = "https://detail.m.tmall.com/item.htm?id=" . $id . "&tbpm=3";
        $response = $this->http_curl($url);
        $response = mb_convert_encoding($response, 'UTF-8', 'UTF-8,GBK,GB2312,BIG5');
        preg_match_all('/data-ks-lazyload="(http.+?)"/i', $response, $matches);
        $arr = array();
        foreach ($matches[1] as $k => $v) {
            $arr[] = "<p>" .
                "<img src=" ."'".$v ."'" ."/>".
                "</p>";
        }
        $str = implode('', $arr);//把数组元素组合为一个字符串
        if(!empty($str)){
            session('detailed', $str);
            exit(json_encode(['code' => 1, 'msg' => '采集成功id为'.$id]));
        }else{
            exit(json_encode(['code' => 0, 'msg' => '采集失败,请输入id即可']));
        }
    }

    /**
     *
     * @param type $url
     * @param type $type
     * @param type $arr
     * @return type
     */
    public function http_curl($url, $type = 'get', $arr = '')
    {

        if ($arr) {
            $o = "";
            foreach ($arr as $k => $v) {
                $o .= "$k=" . urlencode($v) . "&";
            }
            $arr = substr($o, 0, -1);
        }

        $ch = curl_init();

        $headers = array(
            "cache-control: no-cache"
        );

        $user_agent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.100 Safari/537.36";

        curl_setopt($ch, CURLOPT_URL, $url); //设置访问的地址
        curl_setopt($ch, CURLOPT_USERAGENT, $user_agent);
//        curl_setopt($ch, CURLOPT_HTTPHEADER,$headers);
//        curl_setopt($ch, CURLOPT_HEADER, 1 );
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //获取的信息返回
        curl_setopt($ch, CURLOPT_REFERER, "www.baidu.com");
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
//        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, TRUE);
//        curl_setopt($ch,CURLOPT_COOKIE,$cookie);
        if ($type == 'post') {
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $arr);
        }
        $output = curl_exec($ch);
        if (curl_error($ch)) {
            return curl_error($ch);
        }
        return $output;

    }



    /**
     * 删除天猫采集商品详细
     * @return array|mixed
     * @throws \think\exception\PDOException
     */
    public function deltaobao()
    {
        ignore_user_abort();
        set_time_limit(0);
        session('detailed', null);
        if(empty($_SESSION['detailed'])){
            exit(json_encode(['code' => 1, 'msg' => '清除成功']));
        }else{
            exit(json_encode(['code' => 0, 'msg' => '清除失败']));
        }
    }

}
